const fs = require('fs');
const path = require('path');

const root = __dirname;
const inputDir = path.join(root, '原始数据');
const outputDir = path.join(root, '输出数据');

const MP_FILE = path.join(inputDir, 'MP 45 AUD 07675060868.txt');
const MPC_FILE = path.join(inputDir, 'MPC 15AUD 07675060867.txt');

const OUT_PARENT = path.join(outputDir, '2316487_MP 45AUD SECURE PACK Parent Perso data.txt');
const OUT_CHILD  = path.join(outputDir, '2316487_MPC 15AUD Child Perso data.txt');
const OUT_MAP    = path.join(outputDir, '2316487_ROLBOX PSA-016293_Multipack Maping file.csv');

function pad6(n) {
  return String(n).padStart(6, '0');
}

function ensureDir(p) {
  if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true });
}

function readLines(file) {
  const text = fs.readFileSync(file, 'utf8');
  return text
    .split(/\r?\n/)
    .map(s => s.trim())
    .filter(s => s.length > 0);
}

function main() {
  ensureDir(outputDir);

  // 1) 读 MP（A列）
  const mpLines = readLines(MP_FILE);
  // 2) 读 MPC（B、C、E列）
  const mpcRaw = readLines(MPC_FILE);
  const mpcRows = [];
  for (const line of mpcRaw) {
    const parts = line.split(',');
    if (parts.length < 5) continue;
    // parts[0]=序号(原始文件自带的索引), parts[1]=B, parts[2]=C, parts[3]=未知/价格, parts[4]=E
    const B = parts[1].trim();
    const C = parts[2].trim();
    const E = parts[4].trim();
    mpcRows.push({ B, C, E });
  }

  // 3) 生成 Parent 输出
  const parentOut = mpLines.map((A, idx) => `${A},${pad6(idx + 1)}`);

  // 4) 生成 Child 输出
  //    - 第1字段：全体连续序号 000001...
  //    - 第5字段：字母+组号，字母按 A/B/C 循环，组号=每3条加1
  const letters = ['A', 'B', 'C'];
  const childOut = mpcRows.map((row, idx) => {
    const seq = pad6(idx + 1);
    const groupNo = pad6(Math.floor(idx / 3) + 1);
    const letter = letters[idx % 3];
    const dField = `${row.E}${row.B}`; // E+B
    return `${seq},${row.B},${row.C},${dField},${letter}${groupNo}`;
  });

  // 5) 生成 Mapping（1个 Parent 对 3 个 Child 的第4列）
  const parentCount = mpLines.length;
  const childCount = mpcRows.length;
  const fullGroups = Math.min(parentCount, Math.floor(childCount / 3));

  if (parentCount * 3 !== childCount) {
    console.warn(
      `[WARN] 数据条数不整除: Parent=${parentCount}, Child=${childCount}, ` +
      `将按完整三联组数量输出 Mapping=${fullGroups}`
    );
  }

  const mapOut = [];
  for (let i = 0; i < fullGroups; i++) {
    const parentA = mpLines[i];
    const c1 = `${mpcRows[i * 3 + 0].E}${mpcRows[i * 3 + 0].B}`;
    const c2 = `${mpcRows[i * 3 + 1].E}${mpcRows[i * 3 + 1].B}`;
    const c3 = `${mpcRows[i * 3 + 2].E}${mpcRows[i * 3 + 2].B}`;
    mapOut.push(`${parentA},${c1},${c2},${c3}`);
  }

  // 6) 写文件（Windows 下用 CRLF 更友好）
  const EOL = '\r\n';
  fs.writeFileSync(OUT_PARENT, parentOut.join(EOL) + EOL, 'utf8');
  fs.writeFileSync(OUT_CHILD,  childOut.join(EOL)  + EOL, 'utf8');
  fs.writeFileSync(OUT_MAP,    mapOut.join(EOL)    + EOL, 'utf8');

  // 7) 输出摘要
  console.log('[DONE] 输出完成：');
  console.log(`  Parent: ${OUT_PARENT} (${parentOut.length} 行)`);
  console.log(`  Child : ${OUT_CHILD} (${childOut.length} 行)`);
  console.log(`  Map   : ${OUT_MAP} (${mapOut.length} 行)`);

  // 8) 打印前3行样例方便人工校验
  console.log('\nSample Parent[1]:', parentOut[0]);
  console.log('Sample Child[1..3]:');
  console.log('  ' + childOut[0]);
  console.log('  ' + childOut[1]);
  console.log('  ' + childOut[2]);
  console.log('Sample Map[1]:', mapOut[0]);
}

main();